from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from core.crud import get_department, create_department, update_department, delete_department
from core.dependencies import get_db, log_route
from core.schemas import DepartmentSchema, ResponseModel

router = APIRouter(
    prefix="/department",
    tags=["部门"],
    responses={404: {"description": "Not found"}},
)


@router.post("/")
async def create_new_department(department: DepartmentSchema, db: Session = Depends(get_db), _=Depends(log_route)):
    department = create_department(db, department)
    return ResponseModel(data=department, code="200", message="success")


@router.get("/{department_id}")
async def read_department(department_id: int, db: Session = Depends(get_db), _=Depends(log_route)):
    department = get_department(db, department_id)
    if department:
        return ResponseModel(data=department.to_dict(), code="200", message="success")
    else:
        return ResponseModel(data=None, code="404", message="Department not found")


@router.put("/{department_id}")
async def update_existing_department(department_id: int, department: DepartmentSchema, db: Session = Depends(get_db), _=Depends(log_route)):
    updated_department = update_department(db, department_id, department)
    if updated_department:
        return ResponseModel(data=updated_department, code="200", message="success")
    else:
        return ResponseModel(data=None, code="404", message="Department not found")


@router.delete("/{department_id}")
async def delete_existing_department(department_id: int, db: Session = Depends(get_db), _=Depends(log_route)):
    deleted_department = delete_department(db, department_id)
    if deleted_department:
        return ResponseModel(data=deleted_department, code="200", message="success")
    else:
        return ResponseModel(data=None, code="404", message="Department not found")
